<?php
/**
 * Created by PhpStorm.
 * User: rocky
 * Date: 2019-07-14
 * Time: 12:06
 */

namespace app\common\tools;


use app\common\exception\ErrorException;
use library\File;
use think\Controller;

class Files extends Controller
{
    //上传文件
    public function upload()
    {
        $file = $this->request->file('file');
        if (!$file->checkExt(strtolower(sysconf('storage_local_exts')))) {
            throw new ErrorException(4005, 200, '上传失败,文件上传类型受限');
        }
        if ($file->checkExt('php,sh')) {
            return new ErrorException(4005, 200, '上传失败,可执行文件禁止上传到本地服务器');
        }
        $tmp_name = $file->getInfo('tmp_name');
        $fileName = md5_file($tmp_name);
        $ext = strtolower(pathinfo($file->getInfo('name'), PATHINFO_EXTENSION));
        $fileName = $fileName . '.' . $ext;
        $url = File::url($fileName);
        if($url){
            return $url;
        }else{
            $res = File::save($fileName,file_get_contents($tmp_name));
            if($res){
                return $res['url'];
            }else{
                throw  new ErrorException(4006, 200, '上传失败');
            }
        }
    }
    private static function imgUrl($val)
    {
        if(!strstr($val, 'http://') && !strstr($val, 'https://') && !empty($val)) {
            $val = File::instance('local')->url(str_replace('upload/', '', $val));
            if ($val == false) {
                return null;
            }
        }
        return $val;
    }

    public static function getImgUrl($val)
    {
        if (is_array($val)) {
            $imgs = array_filter($val);
            $val = [];
            foreach ($imgs as $img) {
                $val[] = self::imgUrl($img);
            }
            return $val;
        } else {
            return self::imgUrl($val);
        }
    }
}